package com.clps.algorithm.chapter13.含有重复元素集合的全排列;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 给你一个有重复数字的集合,请找出它的所有配列,例如集合[1,1,2]有3个全排列,分别是[1, 1, 2]、[1, 2, 1]和[2, 1, 1]
 */
public class demo01 {
    public static void main(String[] args) {

    }

    public  List<List<Integer>> permuteUnique(int[] nums){
        List<List<Integer>> result = new ArrayList<>();
        helper(nums,0,result);
        return result;
    }

    private void helper(int[] nums, int i, List<List<Integer>> result) {
        if(i == nums.length){
            List<Integer> permutation = new ArrayList<>();
            for (int num : nums) {
                permutation.add(num);
            }

            result.add(permutation);
        }else{
            Set<Integer> set = new HashSet<>();
            for (int j = 0; j < nums.length; j++) {
                if(!set.contains(nums[j])){
                    set.add(nums[j]);

                    swap1(nums,i,j);
                    helper(nums,i+1,result);
                    swap1(nums,i,j);
                }

            }
        }
    }

    private void swap1(int[] nums, int i, int j) {
        if(i!=j){
            int temp = nums[i];
            nums[i] = nums[j];
            nums[j] = temp;
        }
    }

}
